//
//  UIFont+xsBossDynamicFont.m
//  digital_robot_demo
//
//  Created by xskj on 2024/9/14.
//

#import "UIFont+xsBossDynamicFont.h"
#import <CoreText/CoreText.h>
//#import "xsBossIPDownloadFont.h"

@implementation UIFont (xsBossDynamicFont)

BOOL xsFileExistsInDirectory(NSString *directoryPath, NSString *fileName) {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = [directoryPath stringByAppendingPathComponent:fileName];
    return [fileManager fileExistsAtPath:filePath];
}
//下载字体文件
+ (void)downloadZipFile:(NSString *)fileUrl toPath:(NSString *)path withResult:(void(^)(NSString *saveFileDataPathUrlString))resultBk
{
    
////    //    NSString *filePath = @"path/to/your/file.txt";
////        NSString *fileName = [filePath lastPathComponent];
////        // 移除扩展名
////        fileName = [fileName stringByDeletingPathExtension];
//
//    NSString *tempDownLoadFileName = [fileUrl lastPathComponent];
//    BOOL isHaveFileData = xsFileExistsInDirectory(path, tempDownLoadFileName);
////    if(isHaveFileData){
////        return;
////    }
//
    __block NSError *error = nil;
    NSURL *url = [NSURL URLWithString:fileUrl];
    NSString *fileName = [url lastPathComponent];
    NSString *zipPath = [path stringByAppendingPathComponent:fileName];
    
    NSMutableURLRequest *mRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:fileUrl]];
    [mRequest setHTTPMethod:@"GET"];
    [mRequest setTimeoutInterval:60*5];
    NSOperationQueue *opqueue = [[NSOperationQueue alloc] init];
    [NSURLConnection sendAsynchronousRequest:mRequest queue:opqueue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        
        if(!connectionError)
        {
            [data writeToFile:zipPath options:0 error:&error];
            if(!error)
            {
                [self registerFont:zipPath];
                resultBk(zipPath);// zipPath;
            }
            else{
                resultBk(nil);
            }
        }
        else{
            resultBk(nil);
        }
        
    }];
   
//    NSData *data = [NSData dataWithContentsOfURL:url options:0 error:&error];
//    if(!error)
//    {
//        [data writeToFile:zipPath options:0 error:&error];
//        if(!error)
//        {
//            [self registerFont:zipPath];
//            return zipPath;
//        }
//    }
//    return nil;
    
    
}
//解压zip压缩包
//iOS中解压zip压缩文件非常方便，使用ZipArchive这个开源项目按照如下的方式即可快速解压zip文件。
//- (NSString *)expandZipFile:(NSString *)src toPath:(NSString *)desc
//{
//    ZipArchive *za = [[ZipArchive alloc] init];
//    if ([za UnzipOpenFile:src])
//    {
//        BOOL ret = [za UnzipFileTo:desc overWrite:YES];//解压文件
//        if(ret)
//        {
//            NSString *zipName = [src lastPathComponent];//获取zip文件的文件名
//            [[NSFileManager defaultManager] removeItemAtPath:zipPath error:nil];//删除zip压缩包
//            zipName = [zipName substringToIndex:[zipName rangeOfString:@".zip"].location];//获取解压到的文件夹
//            return [self.downloadPath stringByAppendingPathComponent:zipName];
//        }
//    }
//    return nil;
//}

//注册指定路径下的字体文件
//下载回来的字体文件如果不做处理是不能直接使用的，使用前需要先注册然后才能使用，注册方式如下：
//需要先引入CoreText框架,
//#import <CoreText/CoreText.h>
+ (void)registerFont:(NSString *)fontPath
{
    NSData *dynamicFontData = [NSData dataWithContentsOfFile:fontPath];
    if (!dynamicFontData)
    {
        return;
    }
    CFErrorRef error;
    CGDataProviderRef providerRef = CGDataProviderCreateWithCFData((__bridge CFDataRef)dynamicFontData);
    CGFontRef font = CGFontCreateWithDataProvider(providerRef);
    
    if (! CTFontManagerRegisterGraphicsFont(font, &error))
    {
        //注册失败
        CFStringRef errorDescription = CFErrorCopyDescription(error);
        NSLog(@"Failed to load font: %@", errorDescription);
        CFRelease(errorDescription);
    }
    
    NSLog(@"font: %@", font);
    CFRelease(font);
    CFRelease(providerRef);
}

//判断字体是否加载
//在使用字体文件前最好是先判断字体是否已经被加载过了，判断方式如下：
+ (BOOL)isFontDownloaded:(NSString *)fontName
{
    UIFont* aFont = [UIFont fontWithName:fontName size:12.0];
    BOOL isDownloaded = (aFont && ([aFont.fontName compare:fontName] == NSOrderedSame || [aFont.familyName compare:fontName] == NSOrderedSame));
    return isDownloaded;
}


/**
 获取导入的自定义字体的名称
 并注册自定义字体到系统字体库，在程序启动后调用一次即可
 适用字体类型：ttf，otf

 @param path 字体文件存放路径，
 @return 自定义字体的名称
 */
+ (NSString *)CXGetCustomFontNameWithPath:(NSString *)path {
    NSURL *fontUrl = [NSURL fileURLWithPath:path];
    CGDataProviderRef fontDataProvider = CGDataProviderCreateWithURL((__bridge CFURLRef)fontUrl);
    CGFontRef fontRef = CGFontCreateWithDataProvider(fontDataProvider);
    CGDataProviderRelease(fontDataProvider);
    CTFontManagerRegisterGraphicsFont(fontRef, NULL);
    NSString *fontName = CFBridgingRelease(CGFontCopyPostScriptName(fontRef));
    CGFontRelease(fontRef);
    return fontName;
}

/**
 获取导入的自定义字体的名称数组
 并注册自定义字体到系统字体库，在程序启动后调用一次即可
 适用字体类型：ttc

 @param path 字体文件存放路径
 @return 自定义字体的名称数组
    */
+ (NSArray *)CXGetCustomFontNameArrayWithPath:(NSString *)path {
    // 注意📢这个方法会崩溃暂时不解决
//    CFStringRef fontPath = CFStringCreateWithCString(NULL, [path UTF8String], kCFStringEncodingUTF8);
//    CFURLRef fontUrl = CFURLCreateWithFileSystemPath(NULL, fontPath, kCFURLPOSIXPathStyle, 0);
//    CFArrayRef fontArray =CTFontManagerCreateFontDescriptorsFromURL(fontUrl);
//    CTFontManagerRegisterFontsForURL(fontUrl, kCTFontManagerScopeNone, NULL);
//    NSMutableArray *customFontArray = [NSMutableArray array];
//    for (CFIndex i = 0 ; i < CFArrayGetCount(fontArray); i++){
//        CTFontDescriptorRef  descriptor = CFArrayGetValueAtIndex(fontArray, i);
//        CTFontRef fontRef = CTFontCreateWithFontDescriptor(descriptor, 15, NULL);
//        NSString *fontName = CFBridgingRelease(CTFontCopyName(fontRef, kCTFontPostScriptNameKey));
//        [customFontArray addObject:fontName];
//    }
//
//    return customFontArray;
    
    return @[];
}


@end
